<?php
/**
 * Created by PhpStorm.
 * User: user1
 * Date: 2018/6/1
 * Time: 9:20
 */

namespace app\common\service;

use app\common\enum\StatusEnum;
use app\common\model\Admin as AdminModel;
use think\Exception;

class LoginService
{
    /**
     * 验证管理员登录信息
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public static function checkLogin() {
        // 验证码
        $captcha = input('param.captcha', '');
        if(!captcha_check($captcha)){
            throw new Exception('验证码错误');
        };

        $username = input('param.username');
        $password = input('param.password');

        // 根据用户名获取账户数据
        $admin = AdminModel::get(['username' => $username]);

        if (!$admin) {
            throw new Exception('账号不存在');
        }

        if ($admin->status != StatusEnum::ADMIN_VALID) {
            throw new Exception('账号状态异常');
        }

        // 验证密码
        $check_password = md5($admin->salt . $password);
        if ($check_password != $admin->password) {
            throw new Exception('密码错误');
        }

        // 创建管理员权限缓存
        JurisdictionService::createAdminJurisdictionCache($admin->role_ids, $admin->id);

        // 验证成功，记录session
        $login_session = [
            'id' => $admin->id,
            'username' => $username,
            'role_ids' => $admin->role_ids,
            'nickname' => $admin->nickname
        ];
        session('szb_admin', $login_session);
    }
}